package com.sitanyun.merchant.guide.base;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.base.utils.NetworkStateUtils;

import java.util.List;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.ButterKnife;


/**
 * Activity 的基类，
 */
public abstract class BaseActivity extends AppCompatActivity implements ICallback, BaseViewAble {
    private boolean isFindViewById;
    public FrameLayout ffMainLayout;
    public ImageView mTvReturn;
    public TextView mTvTitleStr;
    public String mTvRightText;
    public TextView mRightKey;
    public ImageView mImageRightKey;
    public BaseActivity mActivity;
    private static final String TAG = "BaseActivity";
    private String titleStr;
    public int page = 0;
    public FrameLayout ff_main_layout;
    protected ProgressDialog progressDialog;
    //防止重复点击设置的标志，涉及到点击打开其他Activity时，将该标志设置为false，在onResume事件中设置为true
//    protected boolean isDestroy;
//    private boolean clickable=false;

    public static int anInt=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        page = 0;
     //   isDestroy=false;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mActivity = this;
        XActivityStack.getInstance().addActivity(mActivity);
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        if (!NetworkStateUtils.isNetworkConnected(this)) {
          ToastUtil.showToast(this, "网络异常,请稍后重试");
           // this.finish();
         // return;
        }
        //根据状态栏颜色来决定状态栏文字用黑色还是白色
      //  StatusBarUtil.setStatusBarMode(this, true, R.color.XFrame_white);
        ButterKnife.bind(this);
        initData(savedInstanceState);
        initView();
        if (isFindViewById) {
            ffMainLayout = (FrameLayout) findViewById(R.id.ff_main_layout);
            mTvReturn = (ImageView) findViewById(R.id.tv_return);
            mTvTitleStr = (TextView) findViewById(R.id.tv_title_str);
            mTvTitleStr.setText(titleStr);
            mTvReturn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    isFindViewById = false;
                    finish();

                }
            });
        }
     //   isBackground(mActivity);
     //   setImmerseLayout(ffMainLayout);
      //  prepareThirdPushToken();


    }
//    protected void setImmerseLayout(View view) {// view为标题栏
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            Window window = getWindow();
//            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            int statusBarHeight = getStatusBarHeight(this.getBaseContext());
//            view.setPadding(0, statusBarHeight, 0, 0);
//        }
//    }
//    public int getStatusBarHeight(Context context) {
//        int result = 0;
//        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
//                "android");
//        if (resourceId > 0) {
//            result = context.getResources().getDimensionPixelSize(resourceId);
//        }
//        return result;
//    }

//    private void prepareThirdPushToken() {
//        ThirdPushTokenMgr.getInstance().setPushTokenToTIM();
//        if (BrandUtil.isBrandHuawei()) {
//            // 华为离线推送
//            new Thread() {
//                @Override
//                public void run() {
//                    try {
//                        // read from agconnect-services.json
//                        String appId = AGConnectServicesConfig.fromContext(mActivity).getString("client/app_id");
//                        String token = HmsInstanceId.getInstance(mActivity).getToken(appId, "HCM");
//                        Log.i(TAG, "huawei get token:" + token);
//                        if(!TextUtils.isEmpty(token)) {
//                            ThirdPushTokenMgr.getInstance().setThirdPushToken(token);
//                            ThirdPushTokenMgr.getInstance().setPushTokenToTIM();
//                        }
//                    } catch (ApiException e) {
//                        Log.e(TAG, "huawei get token failed, " + e);
//                    }
//                }
//            }.start();
//        } else if (BrandUtil.isBrandVivo()) {
//            // vivo离线推送
//            Log.i(TAG, "vivo support push: " + PushClient.getInstance(getApplicationContext()).isSupport());
//            PushClient.getInstance(getApplicationContext()).turnOnPush(new IPushActionListener() {
//                @Override
//                public void onStateChanged(int state) {
//                    if (state == 0) {
//                        String regId = PushClient.getInstance(getApplicationContext()).getRegId();
//                        Log.i(TAG, "vivopush open vivo push success regId = " + regId);
//                        ThirdPushTokenMgr.getInstance().setThirdPushToken(regId);
//                        ThirdPushTokenMgr.getInstance().setPushTokenToTIM();
//                    } else {
//                        // 根据vivo推送文档说明，state = 101 表示该vivo机型或者版本不支持vivo推送，链接：https://dev.vivo.com.cn/documentCenter/doc/156
//                        Log.i(TAG, "vivopush open vivo push fail state = " + state);
//                    }
//                }
//            });
//        } else if (HeytapPushManager.isSupportPush()) {
//            // oppo离线推送
//            OPPOPushImpl oppo = new OPPOPushImpl();
//            oppo.createNotificationChannel(this);
//            // oppo接入文档要求，应用必须要调用init(...)接口，才能执行后续操作。
//            HeytapPushManager.init(this, false);
//            HeytapPushManager.register(this, PrivateConstants.OPPO_PUSH_APPKEY, PrivateConstants.OPPO_PUSH_APPSECRET, oppo);
//        }
////        else if (BrandUtil.isGoogleServiceSupport()) {
////            // 谷歌推送
////        }
//    }
@Override
protected void onResume() {
    super.onResume();
    anInt++;
}

    @Override
    protected void onPause() {
        super.onPause();
        anInt--;
    }
    @Override
    protected void onStart() {
        super.onStart();
        anInt++;
    }

    @Override
    protected void onStop() {
        super.onStop();
        anInt--;
    }
    public static boolean isBackground(Context context) {


        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    System.out.print(String.format("Foreground App:", appProcess.processName));
                    Log.e("FOREG",appProcess.processName);
                    return false;
                }else{
                    System.out.print("Background App:"+appProcess.processName);
                    Log.e("FOREG",appProcess.processName+"Background App:");
                    return true;
                }
            }
        }
        return false;
    }
    public void setTvRightText(String tvRightText) {
        mTvRightText = tvRightText;
        mRightKey = (TextView) findViewById(R.id.tv_right_key);
        if (mTvRightText != null) {
            mRightKey.setVisibility(View.VISIBLE);
            mRightKey.setText(mTvRightText);
        }
    }

    public void setimageRightText(int image) {
        mImageRightKey = (ImageView) findViewById(R.id.image_right_key);
        mImageRightKey.setImageResource(image);
        mImageRightKey.setVisibility(View.VISIBLE);
    }

    public boolean isFindViewById() {
        return isFindViewById;
    }

    public void setFindViewById(boolean findViewById) {
        isFindViewById = findViewById;
    }

    public void setTitleStr(String titleStr) {
        if (isFindViewById && mTvTitleStr != null && !titleStr.isEmpty()) {
            if (titleStr.length() > 12) {
                mTvTitleStr.setText(titleStr.substring(0, 11));
            } else {
                mTvTitleStr.setText(titleStr);
            }
        }
        this.titleStr = titleStr;
    }

    /**
     * Android M 全局权限申请回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        XPermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 获取点击事件
     */
    @CallSuper
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            View view = getCurrentFocus();
            if (isShouldHideKeyBord(view, ev)) {
                hideSoftInput(view.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 判定当前是否需要隐藏
     */
    protected boolean isShouldHideKeyBord(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            return !(ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom);
        }
        return false;
    }

    /**
     * 隐藏软键盘
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void showLoading() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.show();
    }

    public void hideLoading() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
//    /**
//     * 当前是否可以点击
//     * @return
//     */    protected boolean isClickable(){
//        return clickable;
//
//    }
//    /**
//     * 锁定点击
//     */
//    protected void lockClick(){
//            clickable=false;
//    }

        @Override
     protected void onDestroy() {
        super.onDestroy();

    }
//    @Override
//
//    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
//        if(isClickable()) {
//            lockClick();
//            super.startActivityForResult(intent, requestCode,options);
//
//        }
//
//    }
}
